import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { PageHeader, Table, Space, Button, Modal } from 'antd'
import {
  ExclamationCircleOutlined
 } from '@ant-design/icons';

const { confirm } = Modal;

export default function Audit() {
  const [dataSource, setDataSource] = useState([]);
  const { roleId, region } = JSON.parse(localStorage.getItem('token'));
  useEffect(()=>{
    axios({
      url:`/news?_expand=category&auditState=1`
    }).then(res=>{
      const list = res.data;
      setDataSource(roleId===1? list: list.filter(item => item.region === region && item.roleId !== 2))
    })
  },[region,roleId])
  
  const roleList = ['', '超级管理员', '区域管理员', '区域小编']
  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      render:(title, item)=>{
        // eslint-disable-next-line jsx-a11y/anchor-has-content
        return (
          <a href={`/sandbox/news/preview/${item.id}`}>{title}</a>
        )
      }
    },
    {
      title: '作者',
      dataIndex: 'author'
    },
    {
      title: '身份',
      dataIndex: 'roleId',
      render: (roleId) => {
        return roleList[roleId]
      }
    },
    {
      title: '区域',
      dataIndex: 'region'
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render:(category) => {
        return category.title;
      }
    },
    {
      title: '操作',
      dataIndex: 'auditState',
      render:(auditState, item) => {
        return (
          <Space size="middle">
             <Button type='primary' size='small'  onClick={()=>{
              passaudit(item);
             }}
            >审核通过</Button>
             <Button danger type='primary' size='small' onClick={()=>{
              notpass(item)
             }}
            >不通过</Button>
          </Space>
        )
      }
    },
  ];
  const passaudit = (item) =>{
    confirm({
      title: '审核通过？大人你是认真的吗！',
      icon: <ExclamationCircleOutlined />,
  
      onOk() {
        let list = dataSource;
          list = list.filter((data)=> data.id !== item.id)
          setDataSource(list);
          axios({
            url:`/news/${item.id}`,
            method:'PATCH',
            data:{
              auditState:2,
            }
          })
      },

      onCancel() {
        console.log('Cancel');
      },
    })
  }

  const notpass = (item) =>{
    confirm({
      title: '不给通过吗？呜呜呜',
      icon: <ExclamationCircleOutlined />,
  
      onOk() {
        let list = dataSource;
          list = list.filter((data)=> data.id !== item.id)
          setDataSource(list);
          axios.patch(`/news/${item.id}`,{
            auditState:3
          })
      },

      onCancel() {
        console.log('Cancel');
      },
    })
  }

  return (
    <div>
      <PageHeader
        className="site-page-header"
        title="审核列表"
      />
      <Table dataSource={dataSource} columns={columns} rowKey={item => item.id}/>
    </div>
  )
}
